<template>
  <div class="home-page">

    <div class="banner">
      <div class="container">
        <h1 class="logo-font">conduit</h1>
        <p>A place to share your knowledge.</p>
      </div>
    </div>

    <div class="container page">
      <div class="row">
        <div class="col-md-9">
          <div class="feed-toggle">
            <ul class="nav nav-pills outline-active">
              <li class="nav-item">
                <nuxt-link
                    v-if="user"
                    class="nav-link"
                    :class="{ active: tab === 'your_feed' }"
                    :to="{
                      name: 'home',
                      query: {
                        tab: 'your_feed'
                      }
                    }"
                    exact
                >Your Feed</nuxt-link>
              </li>
              <li class="nav-item">
                <nuxt-link
                    class="nav-link"
                    :class="{ active: tab === 'global_feed' }"
                    :to="{
                      name: 'home',
                    }"
                    exact
                >Global Feed</nuxt-link>
              </li>
              <li class="nav-item" v-if="tag">
                <nuxt-link
                    class="nav-link"
                    :class="{ active: tab === 'tag' }"
                    :to="{
                      name: 'home',
                      query: {
                      	tab: 'tag',
                      	tag: tag
                      }
                    }"
                    exact
                ># {{ tag }}</nuxt-link>
              </li>
            </ul>
          </div>

          <div class="article-preview" v-for="article in articles" :key="article.slug">
            <div class="article-meta">
              <nuxt-link :to="{
              	name: 'profile',
              	params: { username: article.author.username }
              }">
                <img :src="article.author.image" />
              </nuxt-link>
              <div class="info">
                <nuxt-link :to="{
                  name: 'profile',
                  params: { username: article.author.username }
              	}" class="author">{{ article.author.username }}</nuxt-link>
                <span class="date">{{ article.createdAt | date('MMM DD, YYYY') }}</span>
              </div>
              <button class="btn btn-outline-primary btn-sm pull-xs-right"
                      :class="{ active: article.favorited }"
                      @click="onFavorite(article)"
                      :disabled="article.favoritedDisabled"
              >
                <i class="ion-heart"></i> {{ article.favoritesCount }}
              </button>
            </div>
            <nuxt-link class="preview-link" :to="{
                name: 'article',
                params: {
                  slug: article.slug
                }
              }">
              <h1>{{ article.title }}</h1>
              <p>{{ article.description }}</p>
              <span>Read more...</span>
            </nuxt-link>
          </div>
        </div>
        <div class="col-md-3">
          <div class="sidebar">
            <p>Popular Tags</p>

            <div class="tag-list">
              <nuxt-link
                  :to="{
                    name: 'home',
                    query: {
                      tag: item,
                      tab: 'tag'
                    }
                  }"
                  class="tag-pill tag-default"
                  v-for="item in tags" :key="item">{{ item }}</nuxt-link>
            </div>
          </div>
        </div>
      </div>

      <pagination :total="articlesCount" :limit="limit" :page="page" @changePage="changePage" />
    </div>
  </div>
</template>

<script>
  import { getArticles, getYourFeedArticles, addFavorite, deleteFavorite } from "@/api/article"
  import { getTags } from "@/api/tag"
  import Pagination from '@/components/Pagination'
  import { mapState } from 'vuex'

  export default {
  	name: 'Home',
    components: {
      Pagination
    },
    watchQuery: ['page', 'tag', 'tab'],
    async asyncData ({ query }) {
  		const page = Number.parseInt(query.page || 1)
  		const limit = 20
      const tab = query.tab || 'global_feed'
      const tag = query.tag
      const loadArticles = tab === 'global_feed'
        ? getArticles
        : getYourFeedArticles
      const [ articleRes, tagRes ] = await Promise.all([
	      loadArticles({
		      limit,
		      offset: (page - 1) * limit,
          tag: query.tag || ''
	      }),
	      getTags()
      ])

      const { articles, articlesCount } = articleRes.data
      const { tags } = tagRes.data

      articles.forEach(article => article.favoritedDisabled = false)

      return {
  			articles,
        articlesCount,
        tags,
        limit,
        page,
        tab,
	      tag
      }
    },
    computed: {
  		totalPage () {
  			return Math.ceil(this.articlesCount / this.limit)
      },
      ...mapState(['user'])
    },
	  methods: {
		  async onFavorite (article) {
        if (!this.user) {
          this.$router.push({ name: 'register' })
          
          return
        }

		  	article.favoritedDisabled = true
        if (article.favorited) {
        	await deleteFavorite(article.slug)
          article.favorited = false
	        article.favoritesCount -= 1
        } else {
        	await addFavorite(article.slug)
          article.favorited = true
          article.favoritesCount += 1
        }
			  article.favoritedDisabled = false
		  },
      changePage(item) {
        this.$router.push({ name: 'home', query: {
          page: item,
          tag: this.$route.query.tag,
          tab: this.tab
        } })
      }
    }
  }
</script>